Completed
Branch master (7b91a4)
by Elbert
01:07
created

utils.sendToBackground   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 11

Duplication

Lines 11
Ratio 100 %

Importance

Changes 0
Metric Value
cc 4
nc 4
nop 4
dl 11
loc 11
rs 9.2
c 0
b 0
f 0
1
'use strict';
2
3
(function(win) {
4
5
var exports = {};
6
7
(function(exports) {
8
9
	var utils = {
10
		normalizeUrl: function(url) {
11
12
			return this.hashUrl(url) || null;
13
14
		},
15
16
		getReferrer: function() {
17
			return this.normalizeUrl(document.referrer);
18
		},
19
20
		getPageUrl: function() {
21
			return this.normalizeUrl(window.location.href);
22
		},
23
		hashUrl: function(url) {
24
			var a,
25
				result;
26
27
			if ( !url || url.indexOf('http') !== 0 ) {
28
				return null;
29
			}
30
31
			a = document.createElement('a');
32
			a.href = url;
33
34
			result = a.protocol + '//' + a.hostname + '/';
35
36
			if ( a.pathname && a.pathname !== '/' ) {
37
				result += this.hashCode(a.pathname);
38
			}
39
40
			if ( a.search ) {
41
				result += '?' + this.hashCode(a.search);
42
			}
43
44
			if ( a.hash ) {
45
				result += '#' + this.hashCode(a.hash);
46
			}
47
48
			return result;
49
		},
50
51
		hashCode: function(str) {
52
			var hash = 0,
53
				kar,
54
				i;
55
56
			if ( str.length === 0 ) {
57
				return hash;
58
			}
59
60
			for ( i = 0; i < str.length; i++ ) {
61
				kar = str.charCodeAt(i);
62
				hash = ((hash << 5) - hash) + kar;
63
				hash = hash & hash;
64
			}
65
66
			return hash + Math.pow(2, 32);
67
		},
68
69
		realArray: function(a) {
70
			return Array.prototype.slice.apply(a);
71
		},
72
73
		onDocLoaded: function(doc, callback) {
74
			if ( doc.readyState === 'loading' ) {
75
				doc.addEventListener('DOMContentLoaded', callback);
76
			} else {
77
				callback();
78
			}
79
		},
80
81
		SCRIPT_IN_WINDOW_TOP: window === window.top,
82
83
		isFriendlyWindow: function(win) {
84
85
			var href;
86
			try {
87
				href = win.location.href;
88
			} catch(e) {
89
				return false;
90
			}
91
			return true;
92
		},
93
94
		elementWindow: function(el) {
95
			return el.ownerDocument.defaultView;
96
		},
97
98
		viewport: function(win) {
99
			return {width: win.innerWidth, height: win.innerHeight};
100
		},
101
102
		parseQS: function(qs) {
103
			if ( qs.indexOf('http') === 0 ) {
104
				qs = qs.split('?')[1];
105
			}
106
			var i, kvs, key, val;
107
			var dict = {};
108
			qs = qs.split('&');
109
			for ( i = 0; i < qs.length; i++ ) {
110
				kvs = qs[i].split('=');
111
				key = kvs[0];
112
				val = kvs.slice(1).join('=');
113
				try {
114
					dict[key] = window.decodeURIComponent(val);
115
				} catch (e) {
116
117
					continue;
118
				}
119
			}
120
			return dict;
121
		},
122
		sendToBackground: function(message, event, responseMessage, onResponse) {
123
			if ( typeof browser !== 'undefined' ) {
124
				var response = browser.runtime.sendMessage(message);
125
				response.then(onResponse);
126
			} else if ( typeof chrome !== 'undefined' ) {
127
				chrome.runtime.sendMessage(message, onResponse);
128
			} else if ( window.self.port ) {
129
				window.self.port.on(responseMessage, onResponse);
130
				window.self.port.emit(event, message);
131
			}
132
		},
133
134
		ifTrackingEnabled: function(callback, elseCallback) {
135
136
			this.sendToBackground(
137
				'is_tracking_enabled',
138
				'',
139
				'tracking_enabled_response',
140
				function(message) {
141
					if ( message.tracking_enabled ) {
142
143
						callback();
144
					} else {
145
146
						elseCallback();
147
					}
148
				}
149
			);
150
151
		}
152
	};
153
154
	utils.SCRIPT_IN_FRIENDLY_IFRAME = !utils.SCRIPT_IN_WINDOW_TOP && utils.isFriendlyWindow(window.parent);
155
	utils.SCRIPT_IN_HOSTILE_IFRAME = !utils.SCRIPT_IN_WINDOW_TOP && !utils.SCRIPT_IN_FRIENDLY_IFRAME;
156
157
	function LogGenerator() {
158
		this.msgNum = 0;
159
		this.pageMeta = {
160
			'url': utils.getPageUrl(),
161
			'isHP': window.location.pathname === '/',
162
			'referrer': utils.getReferrer(),
163
			'rand': Math.floor(Math.random() * 10e12),
164
			'startTime': new Date().getTime()
165
		};
166
	}
167
168
	LogGenerator.prototype = {
169
		log: function(event, opt_assets, opt_pageTags) {
170
			var opt_video_assets;
171
			if ( event === 'video' || event === 'invalid-video' ) {
172
				opt_video_assets = opt_assets || [];
173
				opt_assets = [];
174
			} else {
175
				opt_video_assets = [];
176
				opt_assets = opt_assets || [];
177
			}
178
			var result = {
179
				doc: this.pageMeta,
180
				event: event,
181
				video_assets: opt_video_assets,
182
				assets: opt_assets,
183
				version: '3',
184
				mrev: '9c4d5b3-c',
185
				msgNum: this.msgNum,
186
				timestamp: new Date().getTime(),
187
				pageVis: document.visibilityState,
188
				pageFoc: document.hasFocus(),
189
				pageTags: opt_pageTags || []
190
			};
191
			this.msgNum++;
192
			return result;
193
		}
194
	};
195
196
	utils.LogGenerator = LogGenerator;
197
198
	exports.utils = utils;
199
})(exports);
200
201
(function(exports) {
202
203
	var SizeMatcher = {
204
		VALID_AD_SIZES: [
205
			[300, 50],
206
			[320, 50],
207
			[160, 600],
208
			[300, 250],
209
			[300, 600],
210
			[300, 1050],
211
			[336, 280],
212
			[336, 850],
213
			[468, 60],
214
			[728, 90],
215
			[728, 250],
216
			[728, 270],
217
			[970, 66],
218
			[970, 90],
219
			[970, 125],
220
			[970, 250],
221
			[970, 400],
222
			[970, 415],
223
			[1280, 100]
224
		],
225
226
		PX_SIZE_TOL: 10,
227
228
		getMatchedAdSize: function(width, height) {
229
230
			if ( !this.set ) {
231
				this.set = this._makeSizeSet();
232
			}
233
234
			return this.set[Math.round(width) + 'x' + Math.round(height)];
235
		},
236
237
		elementIsAdShaped: function(el) {
238
			return !!this.getMatchedAdSizeForElement(el);
239
		},
240
241
		getMatchedAdSizeForElement: function(el) {
242
			var rect = el.getBoundingClientRect();
243
			return this.getMatchedAdSize(rect.width, rect.height);
244
		},
245
246
		_makeSizeSet: function() {
247
			var set = {};
248
			var i;
249
			var xfuz;
250
			var yfuz;
251
			var size;
252
			var width;
253
			var height;
254
255
			for ( i = 0; i < this.VALID_AD_SIZES.length; i++ ) {
256
				for ( xfuz = -this.PX_SIZE_TOL; xfuz <= this.PX_SIZE_TOL; xfuz++ ) {
257
					for ( yfuz = -this.PX_SIZE_TOL; yfuz <= this.PX_SIZE_TOL; yfuz++ ) {
258
						size = this.VALID_AD_SIZES[i];
259
						width = size[0] + xfuz;
260
						height = size[1] + yfuz;
261
						set[width + 'x' + height] = size;
262
					}
263
				}
264
			}
265
			return set;
266
		}
267
	};
268
269
	var Throttler = {
270
		MAX_SEARCHES_PER_WINDOW: 10,
271
		MAX_SEARCHES_PER_ELEMENT: 2,
272
273
		countSearch: function(el) {
274
			if ( typeof el.searches !== 'number' ) {
275
				el.searches = 0;
276
			}
277
278
			el.searches += 1;
279
		},
280
281
		throttle: function(el, max) {
282
			if ( typeof el.searches === 'number' && el.searches >= max ) {
283
				return true;
284
			}
285
			return false;
286
		},
287
288
		throttleElement: function(el) {
289
			return this.throttle(el, this.MAX_SEARCHES_PER_ELEMENT);
290
		},
291
292
		throttleWin: function(win) {
293
			return this.throttle(win, this.MAX_SEARCHES_PER_WINDOW);
294
		},
295
296
		getCount: function(el) {
297
			return el.searches || 0;
298
		}
299
	};
300
301
	function TopSearcher(win) {
302
		this.win = win;
303
		this.doc = win.document;
304
	}
305
306
	TopSearcher.prototype.search = function() {
307
		var candidates = exports.utils.realArray(this.doc.querySelectorAll('img, object, embed')),
308
			html5Ad,
309
			ads = [];
310
311
		ads = ads.concat(candidates.filter(function(el) {
312
			if ( !el.mpAdFound && !Throttler.throttleElement(el) ) {
313
				Throttler.countSearch(el);
314
				if ( (el.tagName !== 'IMG' || isStandardImage(el)) && SizeMatcher.elementIsAdShaped(el) ) {
315
					el.mpAdFound = true;
316
					return true;
317
				}
318
			}
319
			return false;
320
		}));
321
322
		html5Ad = this._mainGetHTMLAd();
323
		if ( html5Ad ) {
324
			html5Ad.html5 = true;
325
			html5Ad.mpAdFound = true;
326
			ads.push(html5Ad);
327
		}
328
329
		return ads;
330
	};
331
332
	TopSearcher.prototype._mainGetHTMLAd = function() {
333
		var styles = this.doc.querySelectorAll('div > style, div > link[rel="stylesheet"]'),
334
			i, div;
335
		for ( i = 0; i < styles.length; i++ ) {
336
			div = styles[i].parentNode;
337
			if ( !div.mpAdFound && SizeMatcher.elementIsAdShaped(div) && this._jumpedOut(div) ) {
338
				return div;
339
			}
340
		}
341
	};
342
343
	TopSearcher.prototype._jumpedOut = function(el) {
344
		var siblings, ifrs;
345
		siblings = exports.utils.realArray(el.parentNode.children);
346
		ifrs = siblings.filter(function(el) {
347
			return el.tagName === 'IFRAME' && el.offsetWidth === 0 && el.offsetHeight === 0;
348
		});
349
		return ifrs.length > 0;
350
	};
351
352
	function IframeSearcher(win) {
353
		this.MIN_AD_AREA = 14000;
354
		this.MIN_WINDOW_PX = 10;
355
356
		this.win = win;
357
		this.doc = win.document;
358
		this.body = win.document.body;
359
		this.winClickTag = win.clickTag;
360
		this.adSizeMeta = this._getAdSizeMeta();
361
		this.numElementsInBody = (this.body && this.body.querySelectorAll('*').length) || 0;
362
363
		this.shouldSearchWindow = false;
364
		if ( !this.win.mpAdFound && this.body && !Throttler.throttleWin(this.win) ) {
365
			this.winWidth = this.win.innerWidth;
366
			this.winHeight = this.win.innerHeight;
367
			if ( this._meetsMinAdSize(this.winWidth, this.winHeight) && !this._containsLargeIframes() ) {
368
				this.shouldSearchWindow = true;
369
			}
370
		}
371
372
	}
373
374
	IframeSearcher.prototype.search = function() {
375
		var ad;
376
377
		if ( this.shouldSearchWindow ) {
378
			ad = this._search();
379
			if ( ad ) {
380
				ad.mpAdFound = true;
381
				win.mpAdFound = true;
382
				return ad;
383
			}
384
			Throttler.countSearch(this.win);
385
		}
386
387
		return null;
388
	};
389
390
	IframeSearcher.prototype._search = function() {
391
		var _this = this,
392
			stdCandidates,
393
			html5Candidates,
394
			stdEl,
395
			html5El;
396
397
		stdCandidates = this.body.querySelectorAll('img, object, embed');
398
399
		stdEl = getFirst(stdCandidates, function(el) {
400
			if ( !el.mpAdFound &&
401
				!Throttler.throttleElement(el) &&
402
				(el.tagName !== 'IMG' || isStandardImage(el)) &&
403
				_this._elementIsAtLeastAsBigAsWindow(el))
404
			{
405
				return true;
406
			}
407
			Throttler.countSearch(el);
408
			return false;
409
		});
410
411
		if ( stdEl ) {
412
			return stdEl;
413
		}
414
415
		if ( this._isHTML5Iframe() ) {
416
			html5Candidates = this.doc.querySelectorAll('body, canvas, button, video, svg, div');
417
			html5El = getFirst(html5Candidates, function(el) {
418
419
				if ( _this._elementIsAtLeastAsBigAsWindow(el) ) {
420
					return true;
421
				}
422
				Throttler.countSearch(el);
423
				return false;
424
			});
425
		}
426
427
		if ( html5El ) {
428
			html5El.html5 = true;
429
			html5El.winClickTag = this.winClickTag;
430
			html5El.adSizeMeta = this.adSizeMeta;
431
			return html5El;
432
		}
433
434
		return null;
435
	};
436
437
	IframeSearcher.prototype._isHTML5Iframe = function() {
438
		if ( this.winClickTag || this.adSizeMeta ) {
439
			return true;
440
		}
441
442
		if ( this.doc.querySelectorAll('canvas', 'button', 'video', 'svg').length > 0 ) {
443
			return true;
444
		}
445
446
		if ( this.numElementsInBody >= 5 && Throttler.getCount(this.win) > 0 && this.doc.querySelectorAll('div').length > 0 ) {
447
			return true;
448
		}
449
450
		return false;
451
	};
452
453
	IframeSearcher.prototype._elementIsAtLeastAsBigAsWindow = function(el) {
454
		var rect = el.getBoundingClientRect(),
455
			tol = 0.95;
456
457
		return rect.width >= (tol * this.winWidth) && rect.height >= (tol * this.winHeight);
458
	};
459
460
	IframeSearcher.prototype._meetsMinAdSize = function(width, height) {
461
		return (width * height) >= this.MIN_AD_AREA;
462
	};
463
464
	IframeSearcher.prototype._containsLargeIframes = function() {
465
		var iframes = this.doc.querySelectorAll('iframe');
466
		var rect;
467
		var i;
468
		for ( i = 0; i < iframes.length; i++ ) {
469
			rect = iframes[i].getBoundingClientRect();
470
			if ( rect.width > this.MIN_WINDOW_PX || rect.height > this.MIN_WINDOW_PX ) {
471
				return true;
472
			}
473
		}
474
		return false;
475
	};
476
477
	IframeSearcher.prototype._getAdSizeMeta = function() {
478
		var adSizeMeta = this.doc.querySelectorAll('meta[name="ad.size"]');
479
		if ( adSizeMeta.length > 0 ) {
480
			return adSizeMeta[0].content;
481
		} else {
482
			return null;
483
		}
484
	};
485
486
	function getFirst(arr, testFn) {
487
		var i, el;
488
		for ( i = 0; i < arr.length; i++ ) {
489
			el = arr[i];
490
			if ( testFn(el) ) {
491
				return el;
492
			}
493
		}
494
		return null;
495
	}
496
497
	function isStandardImage(img) {
498
499
		return img.src && (img.parentNode.tagName === 'A' || img.getAttribute('onclick'));
500
	}
501
502
	function getFriendlyIframes(win) {
503
		var iframes = win.document.querySelectorAll('iframe');
504
		iframes = exports.utils.realArray(iframes);
505
		var friendlyIframes = iframes.filter(function(ifr) {
506
			return exports.utils.isFriendlyWindow(ifr.contentWindow);
507
		});
508
		return friendlyIframes;
509
	}
510
511
	function findAds(win) {
512
		var i,
513
			iframes,
514
			searcher,
515
			ad,
516
			ads = [];
517
518
		if ( win === win.top ) {
519
			searcher = new TopSearcher(win);
520
			ads = ads.concat(searcher.search());
521
		} else {
522
			searcher = new IframeSearcher(win);
523
			ad = searcher.search();
524
			if ( ad ) {
525
				ads.push(ad);
526
			}
527
		}
528
529
		iframes = getFriendlyIframes(win);
530
		for ( i = 0; i < iframes.length; i++ ) {
531
			ads = ads.concat(findAds(iframes[i].contentWindow));
532
		}
533
534
		return ads;
535
	}
536
537
	exports.adfinder = {
538
		getMatchedAdSize: SizeMatcher.getMatchedAdSize.bind(SizeMatcher),
539
		findAds: findAds
540
	};
541
})(exports);
542
543
(function(exports) {
544
545
	var parser = {
546
		TAGS_WITH_SRC_ATTR: {
547
			'IMG': true,
548
			'SCRIPT': true,
549
			'IFRAME': true,
550
			'EMBED': true
551
		},
552
553
		MAX_ATTR_LEN: 100,
554
555
		getUrl: function(el, params) {
556
			var url;
557
558
			if ( this.TAGS_WITH_SRC_ATTR.hasOwnProperty(el.tagName) ) {
559
				url = el.src;
560
561
			} else if ( el.tagName === 'OBJECT' ) {
562
				url = el.data || (params && params.movie) || null;
563
564
			} else if ( el.tagName === 'A' ) {
565
				url = el.href;
566
			}
567
568
			if ( url && url.indexOf('http') === 0 ) {
569
				return url;
570
			} else {
571
				return null;
572
			}
573
		},
574
575
		getParams: function(el) {
576
			if ( el.tagName !== 'OBJECT' ) {
577
				return null;
578
			}
579
580
			var i, child;
581
			var params = {};
582
			var children = el.children;
583
			for ( i = 0; i < children.length; i++ ) {
584
				child = children[i];
585
				if ( child.tagName === 'PARAM' && child.name ) {
586
587
					params[child.name.toLowerCase()] = child.value;
588
				}
589
			}
590
			return params;
591
		},
592
593
		getPosition: function(el) {
594
			var rect = el.getBoundingClientRect();
595
			var win = exports.utils.elementWindow(el);
596
597
			return {
598
				width: Math.round(rect.width),
599
				height: Math.round(rect.height),
600
				left: Math.round(rect.left + win.pageXOffset),
601
				top: Math.round(rect.top + win.pageYOffset)
602
			};
603
		},
604
605
		getFlashvars: function(el, params, url) {
606
			var flashvars;
607
			var urlQS = url && url.split('?')[1];
608
609
			if ( el.tagName === 'EMBED' ) {
610
				flashvars = el.getAttribute('flashvars') || urlQS;
611
612
			} else if ( el.tagName === 'OBJECT' ) {
613
				flashvars = params.flashvars || el.getAttribute('flashvars') || urlQS;
614
			}
615
616
			return (flashvars && exports.utils.parseQS(flashvars)) || null;
617
		},
618
619
		findClickThru: function(el, flashvars) {
620
			var key;
621
			if ( el.tagName === 'IMG' && el.parentElement.tagName === 'A' ) {
622
				return el.parentElement.href;
623
			} else if ( flashvars ) {
624
				for ( key in flashvars ) {
625
					if ( flashvars.hasOwnProperty(key) ) {
626
627
						if ( key.toLowerCase().indexOf('clicktag') === 0 ) {
628
							return flashvars[key];
629
						}
630
					}
631
				}
632
			}
633
			return null;
634
		},
635
636
		getAttr: function(el, name) {
637
			var val = el.getAttribute(name);
638
639
			if ( val && val.slice && val.toString ) {
640
641
				return val.slice(0, this.MAX_ATTR_LEN).toString();
642
			} else {
643
				return null;
644
			}
645
		},
646
647
		putPropIfExists: function(obj, name, val) {
648
			if ( val ) {
649
				obj[name] = val;
650
			}
651
		},
652
653
		putAttrIfExists: function(obj, el, name) {
654
			var val = this.getAttr(el, name);
655
			this.putPropIfExists(obj, name, val);
656
		},
657
658
		elementToJSON: function(el, opt_findClickThru) {
659
			var pos = this.getPosition(el);
660
			var params = this.getParams(el);
661
			var url = this.getUrl(el, params);
662
			var flashvars = this.getFlashvars(el, params, url);
663
			var clickThru = opt_findClickThru && this.findClickThru(el, flashvars);
664
			var json = {
665
				tagName: el.tagName,
666
				width: pos.width,
667
				height: pos.height,
668
				left: pos.left,
669
				top: pos.top,
670
				children: []
671
			};
672
673
			if ( params ) {
674
675
				delete params.flashvars;
676
			}
677
678
			this.putAttrIfExists(json, el, 'id');
679
			this.putAttrIfExists(json, el, 'class');
680
			this.putAttrIfExists(json, el, 'name');
681
682
			this.putPropIfExists(json, 'flashvars', flashvars);
683
			this.putPropIfExists(json, 'url', url);
684
			this.putPropIfExists(json, 'params', params);
685
			this.putPropIfExists(json, 'clickThru', clickThru);
686
687
			return json;
688
		}
689
	};
690
691
	exports.parser = { elementToJSON: parser.elementToJSON.bind(parser) };
692
})(exports);
693
694
(function(exports) {
695
696
	var ContextManager = function(adData) {
697
		this.adData = adData;
698
	};
699
700
	ContextManager.prototype = {
701
		CONTAINER_SIZE_TOL: 0.4,
702
		ASPECT_RATIO_FOR_LEADERBOARDS: 2,
703
704
		isValidContainer: function(el, opt_curWin) {
705
706
			var cWidth = el.clientWidth;
707
			var cHeight = el.clientHeight;
708
709
			var adWidth = this.adData.width;
710
			var adHeight = this.adData.height;
711
712
			var winWidth = opt_curWin && opt_curWin.innerWidth;
713
			var winHeight = opt_curWin && opt_curWin.innerHeight;
714
			var similarWin = opt_curWin && this.withinTol(adWidth, winWidth) && this.withinTol(adHeight, winHeight);
715
716
			var similarSizeX = this.withinTol(adWidth, cWidth);
717
			var similarSizeY = this.withinTol(adHeight, cHeight);
718
			var adAspect = adWidth / adHeight;
719
720
			return similarWin || el.tagName === 'A' || (adAspect >= this.ASPECT_RATIO_FOR_LEADERBOARDS && similarSizeY) || (similarSizeX && similarSizeY);
721
		},
722
723
		withinTol: function(adlen, conlen) {
724
			var pct = (conlen - adlen) / adlen;
725
726
			return pct <= this.CONTAINER_SIZE_TOL;
727
		},
728
729
		serializeElements: function(el) {
730
			if ( !el ) {
731
				return;
732
			}
733
			var i;
734
			var ifrWin;
735
			var adId = this.adData.adId;
736
			var elIsAd = false;
737
738
			if ( adId && el[adId] && el[adId].isAd === true ) {
739
				elIsAd = true;
740
			}
741
742
			var json = exports.parser.elementToJSON(el, elIsAd);
743
			var childJSON;
744
745
			if ( elIsAd ) {
746
				json.adId = adId;
747
				this.adData.element = {};
748
749
				var keys = Object.keys(json);
750
				for ( i = 0; i < keys.length; i++ ) {
751
					var key = keys[i];
752
					if ( key !== 'children' && key !== 'contents' ) {
753
						this.adData.element[key] = json[key];
754
					}
755
				}
756
			}
757
758
			var children = exports.utils.realArray(el.children).filter(function(el) {
759
				var param = el.tagName === 'PARAM';
760
				var inlineScript = el.tagName === 'SCRIPT' && !(el.src && el.src.indexOf('http') >= 0);
761
				var noScript = el.tagName === 'NOSCRIPT';
762
				return !(param || inlineScript || noScript);
763
			});
764
765
			for ( i = 0; i < children.length; i++ ) {
766
				childJSON = this.serializeElements(children[i]);
767
				if ( childJSON ) {
768
					json.children.push(childJSON);
769
				}
770
			}
771
772
			if ( el.tagName === 'IFRAME' ) {
773
				ifrWin = el.contentWindow;
774
775
				if ( adId && el[adId] && el[adId].needsWindow ) {
776
777
					json.contents = this.adData.serializedIframeContents;
778
					el[adId].needsWindow = false;
779
					delete this.adData.serializedIframeContents;
780
781
				} else if ( exports.utils.isFriendlyWindow(ifrWin) ) {
782
783
					childJSON = this.serializeElements(ifrWin.document.documentElement);
784
					if ( childJSON ) {
785
						json.contents = childJSON;
786
					}
787
				}
788
			}
789
790
			if ( json.children.length > 0 || json.adId || json.tagName === 'IFRAME' || json.url ) {
791
				return json;
792
			} else {
793
				return null;
794
			}
795
		},
796
797
		captureHTML: function(containerEl) {
798
			this.adData.context = this.serializeElements(containerEl);
799
		},
800
801
		nodeCount: function(el) {
802
			return el.getElementsByTagName('*').length + 1;
803
		},
804
805
		highestContainer: function(curWin, referenceElement) {
806
			var curContainer = referenceElement;
807
			var docEl = curWin.document.documentElement;
808
			var parentContainer;
809
810
			if ( curWin !== curWin.top && this.isValidContainer(docEl, curWin) ) {
811
				return docEl;
812
			}
813
814
			while ( true ) {
815
				parentContainer = curContainer.parentElement;
816
				if ( parentContainer && this.isValidContainer(parentContainer) ) {
817
					curContainer = parentContainer;
818
				} else {
819
					return curContainer;
820
				}
821
			}
822
		}
823
	};
824
825
	var tagfinder = {
826
827
		setPositions: function(adData, opt_el, opt_winPos) {
828
			var el = opt_el || adData.context;
829
			var winPos = opt_winPos || {left: 0, top: 0};
830
			var ifrPos;
831
832
			el.left += winPos.left;
833
			el.top += winPos.top;
834
835
			if ( el.children ) {
836
				el.children.forEach(function(child) {
837
					this.setPositions(adData, child, winPos);
838
				}, this);
839
			}
840
841
			if ( el.contents ) {
842
				ifrPos = {left: el.left, top: el.top};
843
				this.setPositions(adData, el.contents, ifrPos);
844
			}
845
846
			if ( el.adId === adData.adId ) {
847
				adData.element.left = el.left;
848
				adData.element.top = el.top;
849
			}
850
		},
851
852
		appendTags: function(adData, referenceElement) {
853
			var mgr = new ContextManager(adData);
854
			var curWin = exports.utils.elementWindow(referenceElement);
855
			var highestContainer;
856
857
			while ( true ) {
858
				highestContainer = mgr.highestContainer(curWin, referenceElement);
859
				mgr.captureHTML(highestContainer);
860
				if ( curWin === curWin.top ) {
861
					break;
862
				} else {
863
864
					curWin.mpAdFound = true;
865
866
					mgr.adData.serializedIframeContents = mgr.adData.context;
867
868
					if ( exports.utils.isFriendlyWindow(curWin.parent) ) {
869
						referenceElement = curWin.frameElement;
870
						referenceElement[mgr.adData.adId] = {needsWindow: true};
871
						curWin = curWin.parent;
872
					} else {
873
						break;
874
					}
875
				}
876
			}
877
			return {
878
				referenceElement:referenceElement,
879
				highestContainer: highestContainer
880
			};
881
		}
882
	};
883
884
	exports.tagfinder = tagfinder;
885
})(exports);
886
887
(function(exports) {
888
	var _onAdFound;
889
	var _logGen = new exports.utils.LogGenerator();
890
	var _pageTags;
891
	var INIT_MS_BW_SEARCHES = 2000;
892
	var PAGE_TAG_RE = new RegExp('gpt|oascentral');
893
	var POST_MSG_ID = '1490888598-28717-31700-14775-21098';
894
	var AD_SERVER_RE = new RegExp('^(google_ads_iframe|oas_frame|atwAdFrame)');
895
896
	function getPageTags(doc) {
897
		var scripts = doc.getElementsByTagName('script');
898
		var pageTags = [];
899
		scripts = exports.utils.realArray(scripts);
900
		scripts.forEach(function(script) {
901
			if ( PAGE_TAG_RE.exec(script.src) ) {
902
				pageTags.push({'tagName': 'SCRIPT', 'url': script.src});
903
			}
904
		});
905
		return pageTags;
906
	}
907
908
	function messageAllParentFrames(adData) {
909
910
		adData.postMessageId = POST_MSG_ID;
911
912
		adData = JSON.stringify(adData);
913
914
		var win = window;
915
		while ( win !== win.top ) {
916
			win = win.parent;
917
			win.postMessage(adData, '*');
918
		}
919
	}
920
921
	function appendTagsAndSendToParent(adData, referenceElement) {
922
		var results = exports.tagfinder.appendTags(adData, referenceElement);
923
		if ( exports.utils.SCRIPT_IN_HOSTILE_IFRAME ) {
924
			messageAllParentFrames(adData);
925
926
		} else if ( exports.utils.SCRIPT_IN_WINDOW_TOP ) {
927
928
			exports.tagfinder.setPositions(adData);
929
930
			adData.matchedSize = exports.adfinder.getMatchedAdSize(adData.width, adData.height);
931
			if ( !adData.matchedSize ) {
932
933
				if ( AD_SERVER_RE.exec(results.referenceElement.id) ) {
934
					adData.matchedSize = [adData.width, adData.height];
935
					adData.oddSize = true;
936
				} else {
937
938
					return;
939
				}
940
			}
941
			delete adData.width;
942
			delete adData.height;
943
			adData.curPageUrl = exports.utils.getPageUrl();
944
			_pageTags = _pageTags || getPageTags(document);
945
			var log = _logGen.log('ad', [adData], _pageTags);
946
947
			if ( _onAdFound ) {
948
949
					_onAdFound(log, results.referenceElement);
950
951
			}
952
		}
953
	}
954
955
	function extractAdsWrapper() {
956
		if ( exports.utils.SCRIPT_IN_WINDOW_TOP || document.readyState === 'complete' ) {
957
			extractAds();
958
		}
959
		setTimeout(
960
			function() { extractAdsWrapper(); }, INIT_MS_BW_SEARCHES
961
		);
962
	}
963
964
	function extractAds() {
965
		var ads = exports.adfinder.findAds(window);
966
		ads.forEach(function(ad) {
967
968
			var startTime = new Date().getTime();
969
			var adId = startTime + '-' + Math.floor(Math.random() * 10e12);
970
971
			var adData = {
972
				width: Math.round(ad.offsetWidth),
973
				height: Math.round(ad.offsetHeight),
974
				startTime: startTime,
975
				adId: adId,
976
				html5: ad.html5 || false
977
			};
978
979
			if ( ad.html5 ) {
980
				adData.adSizeMeta = ad.adSizeMeta || null;
981
				adData.winClickTag = ad.winClickTag || null;
982
			}
983
984
			ad[adId] = { isAd: true };
985
986
			appendTagsAndSendToParent(adData, ad);
987
		});
988
	}
989
990
	function isChildWin(myWin, otherWin) {
991
		var parentWin = otherWin.parent;
992
		while ( parentWin !== otherWin ) {
993
			if ( parentWin === myWin ) {
994
				return true;
995
			}
996
			otherWin = parentWin;
997
			parentWin = parentWin.parent;
998
		}
999
		return false;
1000
	}
1001
1002
	function iframeFromWindow(win, winToMatch) {
1003
		var i, ifr, ifrWin,
1004
			iframes = win.document.querySelectorAll('iframe');
1005
1006
		for ( i = 0; i < iframes.length; i++ ) {
1007
			ifr = iframes[i];
1008
			if ( ifr.contentWindow === winToMatch ) {
1009
				return ifr;
1010
			}
1011
		}
1012
1013
		for ( i = 0; i < iframes.length; i++ ) {
1014
			ifrWin = iframes[i].contentWindow;
1015
			if ( exports.utils.isFriendlyWindow(ifrWin) ) {
1016
				ifr = iframeFromWindow(ifrWin, winToMatch);
1017
				if ( ifr ) {
1018
					return ifr;
1019
				}
1020
			}
1021
		}
1022
	}
1023
1024
	function onPostMessage(event) {
1025
		var adData,
1026
			ifrWin = event.source,
1027
1028
			myWin = window.document.defaultView,
1029
			ifrTag;
1030
1031
		try {
1032
1033
			adData = JSON.parse(event.data);
1034
		} catch(e) {
1035
1036
			return;
1037
		}
1038
1039
		if ( adData.postMessageId === POST_MSG_ID ) {
1040
1041
			delete adData.postMessageId;
1042
1043
			event.stopImmediatePropagation();
1044
1045
			if ( isChildWin(myWin, ifrWin) ) {
1046
				if ( exports.utils.isFriendlyWindow(ifrWin) ) {
1047
					ifrTag = ifrWin.frameElement;
1048
				} else {
1049
					ifrTag = iframeFromWindow(myWin, ifrWin);
1050
				}
1051
1052
				if ( ifrTag ) {
1053
					ifrTag[adData.adId] = {needsWindow: true};
1054
					appendTagsAndSendToParent(adData, ifrTag);
1055
				}
1056
			}
1057
		}
1058
	}
1059
1060
	function onVideoMessage(msg, sender, callback) {
1061
		var log;
1062
		if ( msg.event === 'new-video-ad' ) {
1063
			msg.assets.forEach(function(asset) {
1064
1065
			});
1066
			log = _logGen.log('video', msg.assets);
1067
		} else {
1068
			log = _logGen.log('invalid-video', msg.assets);
1069
		}
1070
1071
		msg.assets.forEach(function(a) {delete a.isVideo;});
1072
		log.displayAdFound = msg.displayAdFound;
1073
		log.requests = msg.requests;
1074
		log.data = msg.event_data;
1075
1076
		log.doc.finalPageUrl = log.doc.url;
1077
		log.doc.url = exports.utils.normalizeUrl(msg.origUrl);
1078
1079
		_onAdFound(log);
1080
	}
1081
1082
	function addBackgroundListener(event, callback) {
1083
		if ( typeof browser !== 'undefined' ) {
1084
			browser.runtime.onMessage.addListener(function(msg) {
1085
				if ( msg.event === event ) {
1086
					callback(msg);
1087
				}
1088
			});
1089
		} else if ( typeof chrome !== 'undefined' ) {
1090
			chrome.runtime.onMessage.addListener(function(msg) {
1091
				if ( msg.event === event ) {
1092
					callback(msg);
1093
				}
1094
			});
1095
		} else if ( window.self.port ) {
1096
			window.self.port.on(event, callback);
1097
		}
1098
	}
1099
1100
	exports.coordinator = {
1101
		addPostMessageListener: function() {
1102
			if ( !exports.utils.SCRIPT_IN_FRIENDLY_IFRAME ) {
1103
				window.addEventListener('message', onPostMessage, false);
1104
			}
1105
		},
1106
1107
		init: function(onAdFound) {
1108
1109
			if ( exports.utils.SCRIPT_IN_FRIENDLY_IFRAME ) {
1110
				return false;
1111
			}
1112
1113
			_onAdFound = onAdFound;
1114
			if ( exports.utils.SCRIPT_IN_WINDOW_TOP ) {
1115
				var log = _logGen.log('page');
1116
				onAdFound(log);
1117
1118
				window.addEventListener('beforeunload', function(event) {
1119
					var log = _logGen.log('unload');
1120
					log.timing = window.performance.timing;
1121
					onAdFound(log);
1122
				});
1123
1124
				addBackgroundListener('new-video-ad', onVideoMessage);
1125
				addBackgroundListener('new-invalid-video-ad', onVideoMessage);
1126
1127
			}
1128
1129
			exports.utils.onDocLoaded(document, extractAdsWrapper);
1130
		}
1131
	};
1132
1133
})(exports);
1134
1135
if ( exports.utils.SCRIPT_IN_WINDOW_TOP ) {
1136
	window.adparser = {
1137
		init: exports.coordinator.init,
1138
		addPostMessageListener: exports.coordinator.addPostMessageListener,
1139
		ifTrackingEnabled: exports.utils.ifTrackingEnabled,
1140
		sendToBackground: exports.utils.sendToBackground
1141
	};
1142
} else {
1143
	exports.coordinator.addPostMessageListener();
1144
	exports.utils.ifTrackingEnabled(
1145
		function() {
1146
			exports.coordinator.init(function() {});
1147
		},
1148
		function() {}
1149
	);
1150
}
1151
})(window);
1152
(function(adparser) {
1153
	function onAdFound(log) {
1154
		adparser.sendToBackground({ id: 'ad_log', subject: log }, 'ad_log', '', function(){});
1155
	}
1156
1157
	if (  window === window.top  ) {
1158
		adparser.addPostMessageListener();
1159
		adparser.ifTrackingEnabled(
1160
			function() {
1161
				adparser.init(onAdFound);
1162
			},
1163
			function() {}
1164
		)
1165
	}
1166
})(window.adparser);
1167